package com.wx.mybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * @ClassName DataSourceTwoConfig
 * @Author wx
 * @Description 数据源-2配置
 * @Date 2018-12-27-21:56
 */
@Configuration
@MapperScan(basePackages = "com.wx.mybatis.dao2",sqlSessionTemplateRef = "twoSqlSessionTemplate")
public class DataSourceTwoConfig {


    /**
     * @methodName: twoDataSource
     * @author: wx
     * @description: 注入数据源-1
     * @param 
     * @date: 2018/12/27
     * @return: javax.sql.DataSource
     */
    @Bean(name = "twoDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dbtwo")
    public DataSource twoDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    /**
     * @methodName: twoSqlSessionFactory
     * @author: wx
     * @description: 创建工厂
     * @param dataSource
     * @date: 2018/12/27
     * @return: org.apache.ibatis.session.SqlSessionFactory
     */
    @Bean(name = "twoSqlSessionFactory")
    public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/wx/mybatis/dao2/*.xml"));
        return bean.getObject();
    }

    /**
     * @methodName: twoDataSourceTransactionManager
     * @author: wx
     * @description: 创建事务
     * @param dataSource
     * @date: 2018/12/27
     * @return: org.springframework.jdbc.datasource.DataSourceTransactionManager
     */
    @Bean(name = "twoDataSourceTransactionManager")
    public DataSourceTransactionManager twoDataSourceTransactionManager(@Qualifier("twoDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
    
    /**
     * @methodName: twoSqlSessionTemplate
     * @author: wx
     * @description: 创建模板
     * @param sqlSessionFactory
     * @date: 2018/12/27
     * @return: org.mybatis.spring.SqlSessionTemplate
     */
    @Bean(name = "twoSqlSessionTemplate")
    public SqlSessionTemplate twoSqlSessionTemplate(@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
